package cn.com.dashihui.web.service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;

import cn.com.dashihui.web.dao.SpikeTime;

public class SpikeTimeService {

	public Page<Record> findByPage(int pageNum, int pageSize) {
		StringBuffer sbf = new StringBuffer("FROM t_spike_time a ");
		List<Object> params = new ArrayList<Object>();
		sbf.append("ORDER BY a.id ASC");

		return Db.paginate(pageNum, pageSize, "SELECT a.* ", sbf.toString(), params.toArray());
	}

	public boolean addSpikeTime(SpikeTime newObject) {
		return newObject.save();
	}

	public SpikeTime findById(int id) {

		return SpikeTime.me().findFirst("SELECT * FROM t_spike_time WHERE id=?", id);
	}

	public boolean editSpikeTime(SpikeTime object) {
		return object.update();
	}

	public boolean delSpikeTime(int id) {

		/*return Db.tx(new IAtom() {
			public boolean run() throws SQLException {
				boolean atom = SpikeTime.me().deleteById(id);
				//移除表格中timeid字段中含有的id
				Db.update("UPDATE t_spike_list SET timeid=TRIM(BOTH ',' FROM replace(concat(',',timeid,','), '," + id
						+ ",', ''))");
				//删除union表中和list关联的并且list的timeid字段为空
				//Db.update("DELETE U FROM t_spike_list AS L,t_spike_union AS U WHERE L.id=U.listId AND L.timeid=''");
				//删除活动列表timeid字段值为空的记录
				//Db.update("DELETE L FROM t_spike_list AS L WHERE L.timeid=''");
				return atom;
			}
		});*/
		List<String> list=new ArrayList<String>();
		list.add("DELETE FROM t_spike_time WHERE id="+id);
		Db.batch(list, list.size());
		return true;
		
		
	}
	/*判断time表的id在活动表的timeid字段中是否存在，如果存在，返回true，不存在返回false*/
	public boolean findExistId(int id){
		boolean flag=true;
		//SpikeList.me().findFirst("SELECT * FROM t_spike_list WHERE "+id+" IN timeid");
		List<Record> a=Db.find("SELECT * FROM t_spike_list WHERE FIND_IN_SET ('"+id+"',timeid) limit 1");
		if(a.size()==0){
			flag=false;
		}
		
		return flag;
	}
	public List<SpikeTime> findActiveSpikeTime() {
		return SpikeTime.me().find("SELECT * FROM t_spike_time WHERE state=1");

	}

	public List<SpikeTime> findSelectedSpikeTime() {
		List<SpikeTime> list = new ArrayList<SpikeTime>();
		return SpikeTime.me().find("SELECT T.id,t.begin,t.end FROM t_spike_time T ORDER BY T.id", list.toArray());
	}

	public boolean sortSpike(Map<String, String> sortMap) {
		int batchSize = sortMap.size();
		List<String> sqlList = new ArrayList<String>();
		for (String id : sortMap.keySet()) {
			sqlList.add("UPDATE t_spike_time  WHERE id=" + id);
		}
		int[] result = Db.batch(sqlList, batchSize);
		return result.length > 0;

	}

	/*
	 * public List<Record> listTime() { return Db.find(
	 * "SELECT id,begin,end FROM t_spike_time"); }
	 */
}
